<template>
  <div class="lab-check p-6 bg-gray-50 rounded-lg">
    <!-- 1. 检验查询 Card -->
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <span class="text-lg font-semibold">检验查询</span>
      </template>
      <el-row :gutter="16" align="middle">
        <el-col :span="8">
          <el-input
              v-model="filters.kw"
              placeholder="病历号／姓名"
              clearable
              size="medium"
              prefix-icon="el-icon-search"
              @keyup.enter.native="onSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="medium" @click="onSearch">
            查询
          </el-button>
          <el-button size="medium" @click="onReset">
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 2. 操作按钮 Card -->
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <span class="text-lg font-semibold">操作</span>
      </template>
      <el-space size="medium">
        <el-button
            type="success"
            size="medium"
            :disabled="!canConfirm"
            icon="el-icon-check"
            @click="confirmExecution"
        >
          执行确认
        </el-button>
        <el-button
            type="warning"
            size="medium"
            :disabled="!canCancel"
            icon="el-icon-close"
            @click="cancelExecution"
        >
          取消执行
        </el-button>
        <el-button
            type="primary"
            size="medium"
            :disabled="!canEnterResult"
            icon="el-icon-edit"
            @click="openResultDialog"
        >
          结果录入
        </el-button>
      </el-space>
    </el-card>

    <!-- 3. 数据表格 -->
    <el-card shadow="hover" class="mb-6">
      <template #header>
        <span class="text-lg font-semibold">检验申请列表</span>
      </template>
      <el-table
          :data="apps"
          stripe
          border
          highlight-current-row
          @selection-change="onSelect"
          style="width: 100%;"
          max-height="500"
      >
        <el-table-column type="selection" width="60" />

        <el-table-column
            prop="register.casenumber"
            label="病历号"
            min-width="140"
        />
        <el-table-column
            prop="register.realname"
            label="姓名"
            min-width="120"
        />
        <el-table-column
            prop="apply.name"
            label="项目"
            min-width="200"
        />
        <el-table-column
            prop="apply.state"
            label="状态"
            min-width="100"
            :formatter="row => ['', '新建','已开立','已作废','已缴费','已执行','已完成'][row.apply.state]"
        />
        <el-table-column
            prop="apply.creationtime"
            label="开立时间"
            min-width="180"
        />
      </el-table>
    </el-card>

    <!-- 4. 结果录入对话框 -->
    <el-dialog
        title="录入检验结果"
        v-model="resultDlgVisible"
        width="500px"
        :destroy-on-close="true"
    >
      <el-form :model="resultForm" label-width="80px">
        <el-form-item label="结果">
          <el-input
              type="textarea"
              v-model="resultForm.resultText"
              rows="4"
              placeholder="请输入检验/检查结果"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resultDlgVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResult">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'

const store = useCounterStore()

// — state —
const apps         = ref([])
const selectedRows = ref([])
const filters      = reactive({ kw: '' })

// — 对话框 & 表单 —
const resultDlgVisible = ref(false)
const resultForm       = reactive({ applyId: null, resultText: '' })

// — 按钮可用性 —
const canConfirm     = computed(
    () => selectedRows.value.length === 1 && selectedRows.value[0].apply.state === 4
)
const canCancel      = computed(
    () => selectedRows.value.length === 1 && selectedRows.value[0].apply.state === 5
)
const canEnterResult = computed(
    () => selectedRows.value.length === 1 && selectedRows.value[0].apply.state === 5
)

// — 加载列表 —
async function loadApps() {
  const { data } = await axios.get('/api/doctor/exam/patients', {
    params: {
      caseNumber: filters.kw,
      kw:         filters.kw
    },
    headers: { 'X-User-Id': store.userId }
  })
  apps.value = data
  selectedRows.value = []
}

// — 查询 & 重置 —
function onSearch() { loadApps() }
function onReset() {
  filters.kw = ''
  loadApps()
}

// — 选中行 —
function onSelect(rows) {
  selectedRows.value = rows
}

// — 执行确认 4→5 —
async function confirmExecution() {
  const applyId = selectedRows.value[0].apply.id
  await axios.post(
      '/api/doctor/exam/execute',
      { applyId },
      { headers: { 'X-User-Id': store.userId } }
  )
  await loadApps()
}

// — 取消执行 5→4 —
async function cancelExecution() {
  const applyId = selectedRows.value[0].apply.id
  await axios.post(
      '/api/doctor/exam/cancel',
      { applyId },
      { headers: { 'X-User-Id': store.userId } }
  )
  await loadApps()
}

// — 打开结果录入对话框 —
function openResultDialog() {
  const { apply } = selectedRows.value[0]
  resultForm.applyId   = apply.id
  resultForm.resultText = ''
  resultDlgVisible.value = true
}

// — 提交结果 5→6 —
async function submitResult() {
  await axios.post(
      '/api/doctor/exam/result',
      {
        applyId:    resultForm.applyId,
        resultText: resultForm.resultText
      },
      { headers: { 'X-User-Id': store.userId } }
  )
  resultDlgVisible.value = false
  await loadApps()
}

// — 初始加载 —
onMounted(loadApps)
</script>

<style scoped>
.lab-check {
  background: #f9fafb;
  border-radius: 8px;
}
.mb-6 {
  margin-bottom: 24px;
}
/* 确保卡片内部 table 始终撑满宽度 */
.el-card .el-table {
  width: 100%;
}
</style>
